//
// Created by shen on 2024/6/22.
//

#include "MyGLRenderContext.h"
#include "../util/LogUtil.h"
#include "TriangleSample.h"


MyGLRenderContext* MyGLRenderContext::m_pContext = nullptr;

void MyGLRenderContext::OnSurfaceCreated() {

    glClearColor(256.0f,256.0f,256.0f, 1.0f);
}
MyGLRenderContext::MyGLRenderContext()
{

}

void MyGLRenderContext::SetImageData(int format, int width, int height, uint8_t *pData)
{
    LOGCATE("MyGLRenderContext::SetImageData format=%d, width=%d, height=%d, pData=%p", format, width, height, pData);
    NativeImage nativeImage;
    nativeImage.format = format;
    nativeImage.width = width;
    nativeImage.height = height;
    nativeImage.ppPlane[0] = pData;

    switch (format)
    {
        case IMAGE_FORMAT_NV12:
        case IMAGE_FORMAT_NV21:
            nativeImage.ppPlane[1] = nativeImage.ppPlane[0] + width * height;
            break;
        case IMAGE_FORMAT_I420:
            nativeImage.ppPlane[1] = nativeImage.ppPlane[0] + width * height;
            nativeImage.ppPlane[2] = nativeImage.ppPlane[1] + width * height / 4;
            break;
        default:
            break;
    }

    if (m_pCurSample)
    {
        m_pCurSample->LoadImage(&nativeImage);
    }

}

 MyGLRenderContext *MyGLRenderContext::GetInstance(){
     LOGCATE("MyGLRenderContext::GetInstance");
     if (m_pContext== nullptr){
         m_pContext=new MyGLRenderContext();
     }
     return m_pContext;
}
MyGLRenderContext::~MyGLRenderContext()
{

}

void MyGLRenderContext::OnDrawFrame() {
    LOGCATE("MyGLRenderContext::OnDrawFrame");
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    if (m_pBeforeSample)
    {
//        m_pBeforeSample->Destroy();
//        delete m_pBeforeSample;
//        m_pBeforeSample = nullptr;
    }

    if (m_pCurSample)
    {
        m_pCurSample=new TriangleSample();


    }
    m_pCurSample->Init();
    m_pCurSample->Draw(m_ScreenW, m_ScreenH);

}

void MyGLRenderContext::DestroyInstance()
{
    LOGCATE("MyGLRenderContext::DestroyInstance");
    if (m_pContext)
    {
        delete m_pContext;
        m_pContext = nullptr;
    }

}

void MyGLRenderContext::OnSurfaceChanged(int width, int height) {
    glViewport(0, 0, width, height);
    m_ScreenW = width;
    m_ScreenH = height;
}